package cloud.keveri.gateway.core;

import cloud.keveri.gateway.core.chain.DefaultKeveriPluginChain;
import cloud.keveri.gateway.plugin.api.KeveriPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 作者：沈自在
 **/
@Slf4j
@Component("engineHandler")
public final class GatewayWebHandler implements WebHandler {

    /**
     * 插件
     */
    private final List<KeveriPlugin> plugins;

    public GatewayWebHandler(final List<KeveriPlugin> plugins) {
        // 1. 排序 插件
        this.plugins = plugins.stream()
                .sorted(Comparator.comparingInt(KeveriPlugin::getOrder)).toList();
    }

    /**
     *
     */
    @Override
    public @NonNull Mono<Void> handle(@NonNull ServerWebExchange exchange) {
        log.info("[Keveri-Gateway] 网关接收到请求请求：{}", exchange.getRequest().getPath());
        return new DefaultKeveriPluginChain(plugins).execute(exchange);
    }
}